package com.projectplace.GUI.adapter;

/*
 * Copyright (c) 2011 Projectplace International AB
 * Permission is hereby granted, free of charge, to any person 
 * obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, 
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:The above copyright notice and this 
 * permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import com.projectplace.R;
import com.projectplace.SingeltonPPClient;
import com.projectplace.api.UserApi;
import com.projectplace.api.objectResponses.Conversation.Conversation;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class Conversation_ProjectConversation_Adapter extends BaseAdapter {
	
	private List<Conversation> project;
	@SuppressWarnings("unused")
	private final String LOG_TAG = "Conversation_ProjectConversation_Adapter";
	private Activity activity;
	private static LayoutInflater inflater = null;
	private HashMap<String, Bitmap> bitHash;

	public Conversation_ProjectConversation_Adapter(Activity activity,
			List<Conversation> project) {
		this.activity = activity;
		this.project = project;
		inflater = (LayoutInflater) this.activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		bitHash = new HashMap<String, Bitmap>();

	}

	public int getCount() {
		return project.size();
	}

	public Conversation getItem(int position) {
		return project.get(position);
	}

	public long getItemId(int position) {
		return Long.valueOf(project.get(position).getId());
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder; 
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.conversationrow, parent,
					false);
			holder = new ViewHolder();
			holder.listitem_pic = (ImageView) convertView
					.findViewById(R.id.image);
			holder.listitem_title = (TextView) convertView
					.findViewById(R.id.title);
			holder.listitem_desc = (TextView) convertView
					.findViewById(R.id.description);
			holder.listitem_date = (TextView) convertView.findViewById(R.id.date);
			holder.listitem_likes = (TextView) convertView.findViewById(R.id.likes);
			holder.listitem_comment = (TextView) convertView.findViewById(R.id.comments);
			holder.listitem_likePic = (ImageView) convertView.findViewById(R.id.imageLike);
			holder.listitem_commentPic = (ImageView) convertView.findViewById(R.id.imageComment);
			convertView.setTag(holder);
			
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		final Conversation projConv = project.get(position);

		if (projConv != null) {
			holder.listitem_title.setText(projConv.getPosts().get(0)
					.getAuthor_id());
			
			//Can't initiate Calendar so we get the instance
			Calendar cal = Calendar.getInstance();
			//Takes millisec and the answer from the apis is in sec so multiply by 1000
    		cal.setTimeInMillis(1000*Long.valueOf(projConv.getPosts().get(0).getCreated_time()));
    		
    		holder.listitem_date.setText(
    	            new StringBuilder()
    	                    // Month is 0 based so add 1
                    		.append(cal.get(Calendar.DAY_OF_MONTH)).append("/")
    	                    .append(cal.get(Calendar.MONTH) + 1).append("/")
    	                    .append(cal.get(Calendar.YEAR)).append(" ")
    	                    .append(pad(cal.get(Calendar.HOUR_OF_DAY))).append(":")
    	                    .append(pad(cal.get(Calendar.MINUTE))));
		
			holder.listitem_desc.setMaxLines(3);
			holder.listitem_desc.setText(projConv.getPosts().get(0).getMessage());
			
			//Look if a post has any comments
			if(holder.listitem_comment != null){
				if(projConv.getPost_count() > 1){
					holder.listitem_commentPic.setVisibility(0);
					holder.listitem_comment.setTextColor(Color.BLUE);
					holder.listitem_comment.setText("Comments:" +Integer.toString(projConv.getPost_count()));
					//holder.listitem_commentPic.setImageDrawable(activity.getResources().getDrawable(R.drawable.comments));
					
				}
				else
					holder.listitem_comment.setText("");
					holder.listitem_commentPic.setVisibility(4);
			}
				
				
			
			if(holder.listitem_likes != null){
				//Look if someone like this post
				if(projConv.getLiked_by() != null && projConv.getLiked_by().size() > 0){
					holder.listitem_likePic.setVisibility(0);
					holder.listitem_likes.setTextColor(Color.BLUE);
					holder.listitem_likes.setText("Likes: " +Integer.toString(projConv.getLiked_by().size()));
					//Drawable temp = activity.getResources().getDrawable(R.drawable.like);
					//temp.setBounds(6, 6, 6, 6);
					//holder.listitem_likePic.setImageDrawable(temp);
					
				}				
				else
					holder.listitem_likes.setText("");
					holder.listitem_likePic.setVisibility(4);
			}
			
		
			
			
			 
			
			if (bitHash.containsKey(projConv.getPosts().get(0).getAuthor_id()))
				holder.listitem_pic.setImageBitmap(bitHash.get(projConv
						.getPosts().get(0).getAuthor_id()));
			else {
				Bitmap cachedBitmapFromSDCard = BitmapFactory.decodeFile(activity.getFilesDir()
						.toString()
						+ File.separatorChar
						+ projConv.getPosts().get(0).getAuthor_id() + ".png");
				if (cachedBitmapFromSDCard != null) {
					holder.listitem_pic.setImageBitmap(cachedBitmapFromSDCard);
					bitHash.put(projConv.getPosts().get(0).getAuthor_id(),
							cachedBitmapFromSDCard);
				}

				else {
					UserApi.getAvatar(SingeltonPPClient.getInstance(), projConv
							.getPosts().get(0).getAuthor_id(),
							holder.listitem_pic);
				}
			}

		}else{
			holder.listitem_date.setText("");
		}
			
		return convertView;
	}

	 private static String pad(int c) {
	        if (c >= 10)
	            return String.valueOf(c);
	        else
	            return "0" + String.valueOf(c);
	}
	
	static class ViewHolder {
		TextView listitem_title;
		ImageView listitem_pic;
		TextView listitem_desc;
		TextView listitem_date;
		
		TextView listitem_likes;
		TextView listitem_comment;
		ImageView listitem_likePic;
		ImageView listitem_commentPic;
	}

}
